<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Brands extends CI_Controller {
	var $perpage = 20;

		public function __construct() {
		   parent::__construct();
		   if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) redirect('auth/login/'.str_replace("/", ".",$_SERVER['REQUEST_URI']));
		   $this->layout->setlayout('admin/layout');
		   $this->crumps->push('/admin/brands/', 'Бренды');
		   $this->users_rights_model->check_rights(strtolower(get_class()), $this->router->get_method());
	   }

	public function index()	{

		$data['from'] = $from = $this->input->get('from', true);
		if ($from == "") $from = 0;
		$data['pages'] = $pages = $this->db->select()->from('catalog_brands')->limit($this->perpage, $from)->order_by('brand_order','asc')->get()->result_array();

		/* pagination */
		$count = $this->db->select()->from('catalog_brands')->count_all_results();
		if ($from != 0 && sizeof($pages) <= 0 && $count > 0) {
			$pgng = $from - $this->perpage;
			redirect('admin/brands/index/?from='.$pgng);
		}
		$this->load->library('pagination');
		$config['base_url'] = '/admin/brands/index/';
		$config['total_rows'] = $count;
		$config['page_query_string'] = TRUE;
		$config['per_page'] = $this->perpage;
		$this->pagination->initialize($config);
		$data['paging'] = $this->pagination->create_links();
		/* pagination */

		$this->layout->view('admin/brands/index', $data);
	}
	public function edit($id = 0) {
		$this->crumps->push('/admin/brands/'.($id == 0?'add':'edit/'.$id).'/', ($id == 0?"Добавление":"Редактирование"));
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('catalog_brands')->where('brand_id', $id)->get()->row_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/brands');

		if ($id != 0) $page['brands_date'] = date("d.m.Y", $page['brands_date']);

		$form = new jQuickForm('simple');


		$random = md5(time()).md5(md5(time()));

		$form->addElement('hidden', 'random')->setValue($random);
		$form->setLabel(($id == 0?"Добавление":"Редактирование").' брендов');

		$gr = $form->insertGroup()->addClass('col col2');
		$gr->insertInputText('brand_title')->setLabel('Название')->addRuleRequired();
		$form->insertInputCheckbox('brand_main',"Показывать бренд на главной");

		if ($id != 0 && $page['brand_image'] != "") {
			$file = $page['brand_image'];
			$im = getimagesize('./uploads/catalog_brands/'.$id.'/small/'.$file);
			$padding = round((150 - $im[1]) / 2);
			$text = "<div class=\"multi_upload_preview\"><img style='margin: ".$padding."px 0 0 0;' src='/uploads/catalog_brands/".$id."/small/".$file."' alt='Новое изображение' title='Новое изображение' /><a href='#' class='deleteimage' rel=\"one:uploads:catalog_brands:".$id.":".$file."\"><img src='/data/images/icons/delete.png' alt='Удалить' title='Удалить' /></a></div>";
		}

		$form->insertStatic("<div class='loaded_images' id='loaded_images_brand_image_0'>".$text."<br class='cc' /></div>");

		$post_params = array(
			'max_middle_height' => 200,
			'max_middle_width' => 200,
			'max_small_height' => 120,
			'max_small_width' => 120,
			'width' => '200',
			'height' => '200',
			'random' => $random,
			'session' => $this->session->userdata('session_id')
		);
		$form->insertMultiUpload('brand_image', '/admin/tools/upload/catalog_brands/', $post_params, 1, false, 2048000)->setId('brand_image_0')->setLabel('Фотография для бренда')->setComment('Максимум только одна фотография (jpg/png/gif, 1024Kb, 1000*1000px)');

		$form->insertFCKeditor('brand_desc')->setLabel('Описание');
		$form->insertFCKeditor('brand_text')->setLabel('Текст');

		if ($_SERVER['REQUEST_METHOD'] == "POST" && $form->validate()) {
			if ($id == 0) {
				$p_data = $this->input->post();

				if(!$p_data['brand_main'])$p_data['brand_main'] = 0;
				$rand = $p_data['random'];
				unset($p_data['random']);

				$p_data['brand_status'] = 1;
				$p_data['brand_order'] = 1000;

				$this->db->insert('catalog_brands', $p_data);
				$result = $this->db->insert_id();

				$files = $this->tools_model->copyfiles($rand, $result, 'catalog_brands');
				if (sizeof($files) > 0) $this->db->update('catalog_brands', array('brand_image' => $files[0]), array('brand_id' => $result));

				$this->session->set_flashdata('msg', 'Успешно добавлено');
				redirect('admin/brands/edit/'.$result.'/');
			} else {
				$p_data = $this->input->post();

				if(!$p_data['brand_main'])$p_data['brand_main'] = 0;
				$rand = $p_data['random'];
				unset($p_data['random']);

				$files = $this->tools_model->copyfiles($rand, $id, 'catalog_brands');
				if (sizeof($files) > 0) $p_data['brand_image'] = $files[0]; else unset($p_data['brand_image']);

				$this->db->where('brand_id', $id)->update('catalog_brands', $p_data);
				$this->session->set_flashdata('msg', 'Успешно обновлено');
				redirect('admin/brands/edit/'.$id.'/');
			}
		}
		$form->insertInputSubmit(($id == 0?"Добавить":"Сохранить"));

		$form->addDataSource(new HTML_QuickForm2_DataSource_Array($page));
		$data['form'] = $form."";
		$data['js'] = jQuickForm::js()->getJsAll();
		$this->layout->view('admin/brands/edit', $data);
	}
	public function delete($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('catalog_brands')->where('brand_id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/brands');
		$this->db->where('brand_id', $id)->delete('catalog_brands');
		$this->session->set_flashdata('msg', 'Успешно удалено');
		redirect('admin/brands/'.$pgng);
	}
	public function block($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('catalog_brands')->where('brand_id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/brands');
		$this->db->where('brand_id', $id)->update('catalog_brands', array('brand_status' => 0));
		$this->session->set_flashdata('msg', 'Успешно');
		redirect('admin/brands/'.$pgng);
	}
	public function unblock($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('catalog_brands')->where('brand_id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/brands');
		$this->db->where('brand_id', $id)->update('catalog_brands', array('brand_status' => 1));
		$this->session->set_flashdata('msg', 'Успешно');
		redirect('admin/brands/'.$pgng);
	}
	public function add() {
		return $this->edit(0);
	}
	public function order() {
		$p_data = $this->input->post('order');
		foreach ($p_data['brand'] as $key => $val) {
			$this->db->update('catalog_brands', array('brand_order' => $val), array('brand_id' => $key));
		}
		$this->catalog_service_model->updateAllPath();
		$this->session->set_flashdata('msg', 'Успешно');
		redirect('admin/brands/');
	}
	public function item($brand=FALSE)	{
		if(!$brand){
			$this->session->set_flashdata('error', 'Переданы неверные данные');
			redirect('admin/brands/');
		}
		$this->crumps->push('/admin/brands/item/'.$brand.'/', "Сортировка внутри бренда");
		$data['from'] = $from = $this->input->get('from', true);
		if ($from == "") $from = 0;
		$data['pages'] = $pages = $this->db->select()->from('catalog_items')->limit($this->perpage, $from)->where('item_brand',$brand)->order_by('item_brand_order','asc')->get()->result_array();

		/* pagination */
		$count = $this->db->select()->from('catalog_items')->where('item_brand',$brand)->count_all_results();
		if ($from != 0 && sizeof($pages) <= 0 && $count > 0) {
			$pgng = $from - $this->perpage;
			redirect('admin/brands/item/'.$brand.'/?from='.$pgng);
		}
		$this->load->library('pagination');
		$config['base_url'] = '/admin/brands/item/'.$brand.'/';
		$config['total_rows'] = $count;
		$config['page_query_string'] = TRUE;
		$config['per_page'] = $this->perpage;
		$this->pagination->initialize($config);
		$data['paging'] = $this->pagination->create_links();
		/* pagination */

		$this->layout->view('admin/brands/item', $data);
	}
	public function brand_order($back=FALSE) {
		$p_data = $this->input->post('order');
		foreach ($p_data['item'] as $key => $val) {
			$this->db->update('catalog_items', array('item_brand_order' => $val), array('item_id' => $key));
		}
		$this->session->set_flashdata('msg', 'Успешно');
		if(!$back){
			redirect('admin/brands/');
		}
		redirect('admin/brands/item/'.$back.'/');
	}
}